﻿
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
#include "Block.h"

using namespace std;
using namespace cocos2d;

Scene* SceneMain::createScene()
{
  return SceneMain::create();
}

static void problemLoading(const char* filename) noexcept
{
  printf("Error while loading: %s\n", filename);
  printf("HelloWorldScene.cpp\n");
}

bool SceneMain::init()
{
  if (!Scene::init())
  {
	return false;
  }
  lineCount = 0;
  vsize = Director::getInstance()->getVisibleSize();
  layerGame = Layer::create();
  this->addChild(layerGame);
  startGame();

  auto listener = EventListenerTouchOneByOne::create();
  listener->onTouchBegan = CC_CALLBACK_2(SceneMain::onTouch, this);
  Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);

  return true;
}


void SceneMain::menuCloseCallback(Ref* pSender)
{
  Director::getInstance()->end();
}

void SceneMain::startGame()
{
  //addStartLine();
  addNormalLine(0);
  addNormalLine(1);
  addNormalLine(2);
  addNormalLine(3);
  addNormalLine(4);
}

void SceneMain::addStartLine()
{
  try {
	//first line
	auto start = new Block(Size(vsize.width, vsize.height / 4), Color3B::YELLOW);
	start->setLabel("点击黑块开始游戏", 20, Color4B::BLACK);
	layerGame->addChild(start);
	start->index = 0;
  } catch (const exception&e) {
	log("addStartLine %s\n", e.what());
  }
}

void SceneMain::addNormalLine(int index)
{
  try {
	int blockIndex = r() % 4;
	for (int i = 0; i < 4; i++) {
	  auto color = blockIndex == i ? Color3B::BLACK : Color3B::WHITE;
	  auto b = new Block(Size(vsize.width / 4 - 1, vsize.height / 4 - 1), color);
	  b->setPosition(i*vsize.width / 4, index*vsize.height / 4);
	  b->index = index;
	  b->setTag(4);
	  layerGame->addChild(b);
	}
  } catch (const exception&e) {
	log("addNormalLine %s\n", e.what());
  }
}


void SceneMain::moveDown()
{
  auto child = layerGame->getChildren();
  for (auto it = child.begin(); it != child.end(); it++) {
	auto s = dynamic_cast<Block*>(*it);
	//下降
	s->index--;
	s->runAction(
	  Sequence::create(MoveTo::create(0.2f, Vec2(s->getPositionX(), s->index*vsize.height / 4)), nullptr));
	string str = "remove" + to_string((int)s);
	scheduleOnce([=](float) {
	  if (s->index < 0)
		s->removeFromParent();
	}, 0.2f, str);
  }
}

bool SceneMain::onTouch(Touch * t, Event * e)
{
  //遍历按钮
  for (auto n : layerGame->getChildren())
  {

	auto b = dynamic_cast<Block*>(n);

	//判断点击范围
	if (b->index == 0 &&
	  b->getBoundingBox().containsPoint(t->getLocation()))
	{
	  if (b->getColor() == Color3B::BLACK) {
		n->setColor(Color3B::GRAY);
		addNormalLine(5);
		this->moveDown();
		break;
	  }
	}
  }
  return false;
}
